package com.hs.framework.utils

import android.content.Context
import android.speech.tts.TextToSpeech
import android.speech.tts.UtteranceProgressListener
import android.util.Log
import com.hs.framework.BuildConfig
import java.util.*

object Speech {

    private var textToSpeech: TextToSpeech? = null
    private var ready = false
    private const val TAG = "tts"

    fun init(context: Context) {
        textToSpeech = TextToSpeech(context) { status ->
            if (status == TextToSpeech.SUCCESS) {
                val locale = Locale.getDefault()
                if (textToSpeech?.isLanguageAvailable(locale) == TextToSpeech.LANG_AVAILABLE) {
                    textToSpeech?.language = locale
                    ready = true // Mark TTS as ready
                    speak("欢迎使用${BuildConfig.MODULE_NAME}")
                } else {
                    Log.e(TAG, "设备上不支持默认语言的 TextToSpeech $locale")
                }
            } else {
                Log.e(TAG, "TextToSpeech 初始化失败，状态码: $status")
            }
        }
    }

    fun speak(text: String) {
        speak(text, false)
    }

    fun speak(text: String, essential: Boolean) {
        if (!ready) {
            Log.e(TAG, "语音播报尚未初始化好")
            return
        }

        textToSpeech?.let {
            Log.d(TAG, "text:$text,isSpeaking:${it.isSpeaking},essential:$essential")

            if (it.isSpeaking) {
                if (!essential) {
                    return
                }
                it.stop()
            }

            it.speak(text, TextToSpeech.QUEUE_FLUSH, null, "ADBDFD")
            it.setOnUtteranceProgressListener(object : UtteranceProgressListener() {
                override fun onStart(id: String) {
                    Log.d(TAG, "Started speaking: $id")
                }

                override fun onDone(id: String) {
                    Log.d(TAG, "Finished speaking: $id")
                }

                override fun onError(id: String) {
                    Log.e(TAG, "Error speaking: $id")
                }
            })
        } ?: run {
            Log.e(TAG, "TextToSpeech 尚未初始化")
        }
    }

    private fun releaseTTS() {
        textToSpeech?.let {
            try {
                it.stop()
            } catch (e: Exception) {
                Log.e(TAG, "停止 TextToSpeech 时发生异常: ${e.message}")
            }
            try {
                it.shutdown()
            } catch (e: Exception) {
                Log.e(TAG, "关闭 TextToSpeech 时发生异常: ${e.message}")
            }
            textToSpeech = null
        }
    }

    @Throws(Throwable::class)
    fun finalize() {
        releaseTTS()
    }
}
